package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.InspectdatacsmqMapper;
import com.ruoyi.system.mapper.TCalibresultDataMapper;
import com.ruoyi.system.mapper.TWaterlevelshizhiwuchacourseMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ITWaterleveltasksService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 水位计检定任务报送Controller
 * 
 * @author ruoyi
 * @date 2024-07-07
 */
@RestController
@RequestMapping("/system/waterleveltasks")
public class TWaterleveltasksController extends BaseController
{
    @Autowired
    private ITWaterleveltasksService tWaterleveltasksService;
    @Autowired
    private InspectdatacsmqMapper inspectdatacsmqMapper;
    @Autowired
    private  TWaterlevelshizhiwuchacourseMapper cfxMapper;

    @Autowired
    private TCalibresultDataMapper tCalibresultDataMapper;
    /**
     * 查询水位计检定任务报送列表
     */
    @PreAuthorize("@ss.hasPermi('system:waterleveltasks:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWaterleveltasks tWaterleveltasks)
    {
        startPage();
        List<TWaterleveltasks> list = tWaterleveltasksService.selectTWaterleveltasksList(tWaterleveltasks);
        return getDataTable(list);
    }

    /**
     * 导出水位计检定任务报送列表
     */
    @PreAuthorize("@ss.hasPermi('system:waterleveltasks:export')")
    @Log(title = "水位计检定任务报送", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TWaterleveltasks tWaterleveltasks)
    {
        List<TWaterleveltasks> list = tWaterleveltasksService.selectTWaterleveltasksList(tWaterleveltasks);
        ExcelUtil<TWaterleveltasks> util = new ExcelUtil<TWaterleveltasks>(TWaterleveltasks.class);
        util.exportExcel(response, list, "水位计检定任务报送数据");
    }

    /**
     * 获取水位计检定任务报送详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:waterleveltasks:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") String taskId)
    {
        return success(tWaterleveltasksService.selectTWaterleveltasksByTaskId(taskId));
    }

    /**
     * 新增水位计检定任务报送
     */
    @PreAuthorize("@ss.hasPermi('system:waterleveltasks:add')")
    @Log(title = "水位计检定任务报送", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWaterleveltasks tWaterleveltasks)
    {
        return toAjax(tWaterleveltasksService.insertTWaterleveltasks(tWaterleveltasks));
    }

    /**
     * 修改水位计检定任务报送
     */
    @PreAuthorize("@ss.hasPermi('system:waterleveltasks:edit')")
    @Log(title = "水位计检定任务报送", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWaterleveltasks tWaterleveltasks)
    {
        return toAjax(tWaterleveltasksService.updateTWaterleveltasks(tWaterleveltasks));
    }

    /**
     * 删除水位计检定任务报送
     */
    @PreAuthorize("@ss.hasPermi('system:waterleveltasks:remove')")
    @Log(title = "水位计检定任务报送", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
    public AjaxResult remove(@PathVariable String[] taskIds)
    {
        return toAjax(tWaterleveltasksService.deleteTWaterleveltasksByTaskIds(taskIds));
    }



    @PostMapping(value = "/down/{taskId}")
    public void generateAndDownload(@PathVariable String taskId,HttpServletResponse response) throws Exception {
        // 加载模板
        TWaterleveltasks water = tWaterleveltasksService.selectTWaterleveltasksByTaskId(taskId);
        HashMap<String, Object> data = new HashMap<>();

        data.put("water",water);
        TWaterlevelshizhiwuchacourse cfx=cfxMapper.selectWaterOne(taskId);

        data.put("cfx",cfx);
        if (water.getDeviceName().contains("雷达水位计") ) {
            data.put("car","非接触式水位检测装置已通过量值溯源。");
            data.put("res","T/CHES 45-2020《雷达水位计》");
        }
        if (water.getDeviceName().contains("超声波") ) {
            data.put("car","非接触式水位检定装置已通过量值溯源。");
            data.put("res","JJG（交通）034-2015《水运工程 超声波水位计》");
        }
        // 提取年、月、日
        Date calibDate = cfx.getCalibdate();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(calibDate);

        // 解析字符串为年、月、日
        String[] dateParts = formattedDate.split("-");
        int year = Integer.parseInt(dateParts[0]);
        int month = Integer.parseInt(dateParts[1]);
        int day = Integer.parseInt(dateParts[2]);

        data.put("year", year);
        data.put("month", month);
        data.put("day", day);

        List<waterLevel> waterLevel=inspectdatacsmqMapper.selectWaterLevelByTaskId(taskId);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        // 将bz设置为行循环绑定的数据源的key,即key是bz的value会在模板中的{{bz}}处进行解析
        Configure configure = Configure.builder().bind("ww", policy).build();
        List<waterLevel> forms = new ArrayList<>();
        int j=0;
        for (waterLevel waterl:waterLevel){
            j=j+1;
            waterl.setNumber(j);
            if(null!=waterl.getMeasureUp()){
                waterl.setMeasureUp(waterl.getMeasureUp().setScale(2, RoundingMode.HALF_UP));
            }
            if(null!=waterl.getMeasureDown()){
                waterl.setMeasureDown(waterl.getMeasureDown().setScale(2, RoundingMode.HALF_UP));
            }
            if(null!=waterl.getErrorUP()){
                waterl.setErrorUP(waterl.getErrorUP().setScale(2, RoundingMode.HALF_UP));
            }
            if(null!=waterl.getErrorDown()){
                waterl.setErrorDown(waterl.getErrorDown().setScale(2, RoundingMode.HALF_UP));
            }
            if(null!=waterl.getMrad()){
                waterl.setMrad(waterl.getMrad().setScale(2, RoundingMode.HALF_UP));
            }
            forms.add(waterl);
        }
        TCalibresultData  calib=tCalibresultDataMapper.selectTCalibresultDataByTaskid(taskId);
        if(calib!=null){
            if(null!=calib.getAllappearance()&&"1".equals(calib.getAllappearance())){
                calib.setAllappearance("合格");
            }
        }
        data.put("calib",calib);

        data.put("ww",forms);



// 插入一个含有样式的表格
        Tables.TableBuilder tabData = Tables
                // 创建一个指定宽度的表格（docx 文档的 80% 宽度）
                .ofPercentWidth("100%")
                // 表格设为水平居中
                .center();

        tabData.addRow(Rows.of("测次", "盲区", "（标称）m", "标准水位m", "测量水位m")
                // 设置文字颜色
                .textColor("FFFFFF")
                // 设置对应表格的背景颜色
                .bgColor("4472C4")
                // 文字居中
                .center()
                .create()
        );
        List<Inspectdatacsmq> inspectdatacsmq=inspectdatacsmqMapper.selectInspectdatacsmqByTaskId(taskId);
        if(inspectdatacsmq.size()>0){
            for(int i = 0; i < inspectdatacsmq.size(); i++){
                int a=i+1;
                // 输出结果
                tabData.addRow(Rows.of(a+"",inspectdatacsmq.get(i).getMQValue().toString(),inspectdatacsmq.get(i).getBzWaterDeep().toString(),inspectdatacsmq.get(i).getClWaterDeep().toString()).create());
            }
        }
        data.put("mq", tabData.create());

        // 渲染模板
        XWPFTemplate template = XWPFTemplate.compile("D:\\hbsw\\ldshuiweiji.docx",configure).render(data);
        // 设置HTTP响应头，使浏览器知道这是一个Word文档
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=generatedDocument.docx");
        // 输出到HTTP响应流
        template.write(response.getOutputStream());
        template.close();
    }
}
